package bktech.soict.hust.bknote.activity.sms;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.Toast;
import bktech.soict.hust.bknote.R;
import bktech.soict.hust.bknote.activity.sms.QuanLySMS.SMSHolder;

public class QuanLyContact extends Activity {
	ArrayList<String> model = new ArrayList<String>();
	ContactAdapter adapter = null;

	public static final String TAG = "ContactManager";

	private Button mAddAccountButton;
	private ListView mContactList;
	private boolean mShowInvisible;
	private CheckBox mShowInvisibleControl;
	private int selectedPosition;
	private long selectedId;
	private Cursor cursor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.v(TAG, "Activity State: onCreate()");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contact_manager);

		// Obtain handles to UI objects
		mAddAccountButton = (Button) findViewById(R.id.addContactButton);
		mContactList = (ListView) findViewById(R.id.contactList);
		mShowInvisibleControl = (CheckBox) findViewById(R.id.showInvisible);

		// Initialize class properties
		mShowInvisible = false;
		mShowInvisibleControl.setChecked(mShowInvisible);

		// Register handler for UI elements
		
		mContactList = (ListView) findViewById(R.id.contactList);

		mContactList
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						selectedPosition = position;
						selectedId = id;

						showDialog(0);
					}
				});

		mShowInvisibleControl
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						Log.d(TAG, "mShowInvisibleControl changed: "
								+ isChecked);
						mShowInvisible = isChecked;
						populateContactList();
					}
				});

		// Populate the contact list
		populateContactList();
	}

	/**
	 * Populate the contact list based on account currently selected in the
	 * account spinner.
	 */
	private void populateContactList() {
		// Build adapter with contact entries
		cursor = getContacts();

		String[] from = new String[] { ContactsContract.Data.TIMES_CONTACTED,
				ContactsContract.Contacts.DISPLAY_NAME };
		int[] to = { R.id.contactEntryFullname, R.id.contactEntryTimesContacted };

		ContactPhotoAdapter cpa = new ContactPhotoAdapter(this,
				R.layout.contact_entry, cursor, from, to);
		mContactList.setAdapter(cpa);
	}

	/**
	 * Obtains the contact list for the currently selected account.
	 * 
	 * @return A cursor for for accessing the contact list.
	 */
	private Cursor getContacts() {
		// Run query
		Uri uri = ContactsContract.Contacts.CONTENT_URI;
		String[] projection = new String[] { ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME,
				ContactsContract.Data.TIMES_CONTACTED,
				ContactsContract.Contacts.HAS_PHONE_NUMBER };
		String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
				+ (mShowInvisible ? "0" : "1") + "'";
		String[] selectionArgs = null;
		String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
				+ ContactsContract.Data.TIMES_CONTACTED + " DESC, "
				+ " COLLATE LOCALIZED ASC";

		return managedQuery(uri, projection, selection, selectionArgs,
				sortOrder);

	}

	protected Dialog onCreateDialog(int view) {
		Dialog dialog = null;
		ContactDetail.Builder contactDetail = new ContactDetail.Builder(this);

		dialog = contactDetail.create();

		return dialog;
	}

	protected void onPrepareDialog(int id, Dialog dialog) {
		Cursor cur;

		cursor.moveToPosition(selectedPosition);
		int colDisplayName = cursor
				.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
		int colHasNumber = cursor
				.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);

		// Display name
		String displayName = cursor.getString(colDisplayName);
		int hasNumber = cursor.getInt(colHasNumber);
		((ContactDetail) dialog).setDisplayName(displayName);

		// Phone number
		if (hasNumber == 1) {
			cur = getContentResolver().query(
					ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
					ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
					new String[] { String.valueOf(selectedId) }, null);

			cur.moveToFirst();

			int colNumber = cur
					.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
			String number = cur.getString(colNumber);

			cur.close();

			((ContactDetail) dialog).setNumber(number);
		} else
			((ContactDetail) dialog).setNumber("");

		// Phone number
		cur = getContentResolver().query(
				ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
				ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
				new String[] { String.valueOf(selectedId) }, null);

		if (cur.getCount() > 0) {
			cur.moveToFirst();

			int colEmail = cur
					.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
			String email = cur.getString(colEmail);

			cur.close();

			((ContactDetail) dialog).setEmail(email);
		} else
			((ContactDetail) dialog).setEmail("");

		// Contact ID to be able to get the picture later in the Dialog
		// Didn't make it to copy the bitmap from the contact_entry to
		// the contact_detail ImageView.
		((ContactDetail) dialog).setId(selectedId);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(this).inflate(R.menu.optioncontact, menu);

		return (super.onCreateOptionsMenu(menu));
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.searchContact) {
			String message = "selected Search Contact";
			Toast.makeText(this, message, Toast.LENGTH_LONG).show();
			// Search
			launchContactSearch();
			return (true);
		} else if (item.getItemId() == R.id.deleteContact) {
			String message = "selected delete Contact";
			Toast.makeText(this, message, Toast.LENGTH_LONG).show();
			// Search
			launchContactDelete();
			return (true);
		} else if (item.getItemId() == R.id.viewsContact) {
			launchContactList();
			return (true);
		}

		return (super.onOptionsItemSelected(item));
	}

	class ContactAdapter extends ArrayAdapter<String> {
		ContactAdapter() {
			super(QuanLyContact.this, R.layout.row, model);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			SMSHolder holder = null;

			if (row == null) {
				LayoutInflater inflater = getLayoutInflater();
				row = inflater.inflate(R.layout.row, parent, false);
				holder = new SMSHolder(row);
				row.setTag(holder);
			} else {
				holder = (SMSHolder) row.getTag();
			}
			return (row);
		}
	}

	// Search Contact
	protected void launchContactSearch() {
		Intent i = new Intent(this, SearchContact.class);
		startActivity(i);
	}

	// Delete Contact
	protected void launchContactDelete() {
		Intent i = new Intent(this, DeleteContact.class);
		startActivity(i);
	}

	// View Contact
	protected void launchContactList() {
		Intent i = new Intent(this, DeleteContact.class);
		startActivity(i);
	}
}
